import { defineStore } from "pinia";
import { ref } from "vue";
import message_notice from "../functional/message_notice";
import { useRouter } from "vue-router";
import { useUrlStore } from './urlStore';


export const useUserAuthStore = defineStore("user", () => {
    const token = ref("");
    const username = ref("");
    const code = ref(0);    // 状态码,200为登录成功,其他为失败

    const router = useRouter()
    const urlStore = useUrlStore()

    const sign_in = async (user_data: any) => {
        try {
            const res = await fetch(`${urlStore.baseurl}/user/login`, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json"
                },
                body: JSON.stringify(user_data)
            })
            const data = await res.json()
            if (data.code === 200) {
                token.value = data.data.token
                username.value = user_data.userName
                code.value = data.code
            }
            sessionStorage.setItem("token", data.data.token)
            sessionStorage.setItem("username", user_data.userName)
            message_notice("登录成功", "success")
            router.push("/index")
        }
        catch (error: any) {
            message_notice("登录失败", "error")
        }
    }

    const logout = () => {
        token.value = ""
        username.value = ""
        sessionStorage.removeItem("token")
        sessionStorage.removeItem("username")
        message_notice("退出成功", "success")
        router.push("/")
    }

    return { token, username, sign_in, logout, code }
});